package com.glacier.framework.boot.rest.controller;

import com.glacier.framework.boot.rest.utils.FileUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * date 2023-12-31 22:08
 *
 * @author glacier
 * @version 1.0
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @GetMapping("/res1")
    public ResponseEntity<Resource> res1() throws IOException {
        File file = new File(FileUtils.getFileName());
        // 文件不存在返回错误页面
        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }
        // 创建文件资源
        Resource resource = new InputStreamResource(new FileInputStream(file));
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
        // 返回响应实体
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
}
